package com.weixin.paleituo.fragment;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.CouponsActivity;
import com.weixin.paleituo.activity.FloorHomeActivity;
import com.weixin.paleituo.activity.GoodsDetailsActivity;
import com.weixin.paleituo.activity.GoodsListActivity;
import com.weixin.paleituo.activity.HouseDetailsActivity;
import com.weixin.paleituo.activity.LocationMapActivity;
import com.weixin.paleituo.activity.LoginActivity;
import com.weixin.paleituo.activity.MainActivity;
import com.weixin.paleituo.activity.MessageDetailsActivity;
import com.weixin.paleituo.activity.MyMessageActivity;
import com.weixin.paleituo.activity.SearchGoodsActivity;
import com.weixin.paleituo.activity.ShopCarActivity;
import com.weixin.paleituo.adapter.BrandRecommandAdaptet;
import com.weixin.paleituo.adapter.ChoiceStyleGrideAdapter;
import com.weixin.paleituo.adapter.HomeFragmentHorizontalScrollViewAdapter;
import com.weixin.paleituo.adapter.HomeGridViewAdapter;
import com.weixin.paleituo.adapter.HomeRecommandAdapter;
import com.weixin.paleituo.adapter.MyViewPagerAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseFragment;
import com.weixin.paleituo.bean.AdsBean;
import com.weixin.paleituo.bean.HomeBean;
import com.weixin.paleituo.bean.HomeRecommandBean;
import com.weixin.paleituo.bean.MessageBean;
import com.weixin.paleituo.bean.NoticeMessageBean;
import com.weixin.paleituo.bean.ProductListBean;
import com.weixin.paleituo.bean.RecommendStyleList;
import com.weixin.paleituo.bean.RecommendhouseBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.WordOfMouthStoreBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.HeaderAndFooterWrapper;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.LooperTextView;
import com.weixin.paleituo.view.MyGridView;
import com.weixin.paleituo.view.MyHorizontalScrollView;
import com.weixin.paleituo.view.RecommandDividerItemDecoration;
import com.xiaweizi.cornerslibrary.CornersProperty;
import com.xiaweizi.cornerslibrary.RoundCornersTransformation;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Author yichao
 * Time  2017/11/30 9:10
 * Dest  首页
 */
public class HomeFragment extends BaseFragment {

    LinearLayout mLlHorizontalscrollviewFragmentHome;
    MyHorizontalScrollView mIdHorizontalScrollViewFragmentHome;
    @BindView(R.id.iv_search_home_fragment)
    ImageView mIvSearchHomeFragment;
    @BindView(R.id.iv_message_home_fragment)
    ImageView mIvMessageHomeFragment;
    TextView mTvLookallFragmentHome;
    @BindView(R.id.recycle_fragment_home)
    RecyclerView mRecycleFragmentHome;
    private ImageView[] ivPoints;//小圆点图片集合
    public ViewPager viewPager;
    private int totalPage;//总的页数
    private int mPageSize = 8;//每页显示的最大数量
    private List<ProductListBean> listDatas;//总的数据源
    private List<View> viewPagerList;//GridView作为一个View对象添加到ViewPager集合中
    @BindArray(R.array.proName)
    public String[] proName;
    private int[] iconResours = {R.mipmap.new_house, R.mipmap.shopping_mall,R.mipmap.jiaofei, R.mipmap.coupon};
    public ConvenientBanner mConvenientBanner;
    private Context mContext;
    @BindView(R.id.tv_city_fragment_home)
    public TextView mTvLoaction;
    @BindView(R.id.ll_headroot_fragment_home)
    LinearLayout mLinearLayoutRootHead;
    private String mCity;
    private LatLng mLatLng;
    private HomeGridViewAdapter mMyGridViewAdapterer;
    private LoadingPagerHead mLoadingPagerHead;
    private HomeFragmentHorizontalScrollViewAdapter mHomeFragmentHorizontalScrollViewAdapter;
    private View mHeadView;
    private HeaderAndFooterWrapper mHeaderAndFooterWrapper;
    private View mFootView;
    private TextView mTvRecommadn;
    private RelativeLayout mRlNoticeRoot;

    private LooperTextView mLooperTextView;
    private List<NoticeMessageBean> mNoticeMessageBeans;
    private    List<HomeRecommandBean> mHomeRecommandBeans=new ArrayList<>();
    @BindView(R.id.iv_shop_car_fragment_home)
    ImageView ivShopCar;

    private RoundCornersTransformation mRoundCornersTransformation;
    private LinearLayout mLlRecommandRoot;
    private RecyclerView mRecyclerViewRecommand;
    private    List<WordOfMouthStoreBean> mWordOfMouthStoreBeansList=new ArrayList<>();
    private BrandRecommandAdaptet mBrandRecommandAdaptet;
    private HomeRecommandAdapter mHomeRecommandAdapter;
    private MyGridView mMyGridView;
    List<RecommendStyleList> mRecommendStyleLists=new ArrayList<>();
    private ChoiceStyleGrideAdapter mChoiceStyleGrideAdapter;

    @Override
    public View initView(Context context) {
        mContext = context;
        mLoadingPagerHead = new LoadingPagerHead(mContext) {
            @Override
            protected void close() {

            }
            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(mContext, R.layout.fragment_home);
            }

            @Override
            protected void reLoading() {
                retry();
            }

        };

        /*head*/
        mHeadView = UIUtils.inflate(mContext, R.layout.layout_head_home);

        mLlHorizontalscrollviewFragmentHome = mHeadView.findViewById(R.id.ll_horizontalscrollview_fragment_home);
        mIdHorizontalScrollViewFragmentHome = mHeadView.findViewById(R.id.id_horizontalScrollView_fragment_home);

        mTvLookallFragmentHome = mHeadView.findViewById(R.id.tv_lookall_fragment_home);
        viewPager = mHeadView.findViewById(R.id.viewPager);
        mConvenientBanner = mHeadView.findViewById(R.id.id_cb);
        mTvRecommadn = mHeadView.findViewById(R.id.tv_store_recomand_layout_head_home);
      //  View contentView = UIUtils.inflate(context, R.layout.fragment_home);
        LogUtils.i(TAG, "创建 视图 " + "home");
        mRlNoticeRoot = mHeadView.findViewById(R.id.rl_notice_root_layout_head_home);
        mLooperTextView = mHeadView.findViewById(R.id.lloopertextview);
        mMyGridView = mHeadView.findViewById(R.id.gridView_layout_head_home);

        /*foot*/
        mFootView = UIUtils.inflate(mContext, R.layout.layout_foot_homefragment);
        mLlRecommandRoot = mFootView.findViewById(R.id.ll_recommand_root_layout_foot_homefragment);
        mRecyclerViewRecommand = mFootView.findViewById(R.id.recycle_recommand_layout_foot_homefragment);

        return mLoadingPagerHead;
    }
    /**
     * 重新加载
     */
    private void retry() {
        Observable<StatusCode<List<HomeRecommandBean>>> homeRecommand = ApiUtils.getApi().getHomeRecommand(BaseApplication.getUserId(), BaseApplication.getToken(), Contans.rows, 1);


        HttpUtil.getInstance().toSubscribe(homeRecommand, new ProgressSubscriber<List<HomeRecommandBean>>(mContext) {
            @Override
            protected void _onNext(StatusCode<List<HomeRecommandBean>> listStatusCode) {
                List<HomeRecommandBean> homeRecommandBeansData = listStatusCode.getData();
                if (homeRecommandBeansData != null && homeRecommandBeansData.size() > 0) {

                        HomeRecommandAdapter homeRecommandAdapter = new HomeRecommandAdapter(mContext, homeRecommandBeansData);
                        mRecyclerViewRecommand.setItemAnimator(new DefaultItemAnimator());
                      mRecyclerViewRecommand.setLayoutManager(new GridLayoutManager(mContext, 2));
                      mRecyclerViewRecommand.addItemDecoration(new RecommandDividerItemDecoration(mContext));
                    mRecyclerViewRecommand.setAdapter(homeRecommandAdapter);

                }
            }
            @Override
            protected void _onError(String message) {

            }
        },"",lifecycleSubject,false,true);


        Observable<StatusCode<HomeBean>> homeObservable = ApiUtils.getApi().getHomeData(Contans.defaultToken);
        HttpUtil.getInstance().toSubscribe(homeObservable, new ProgressSubscriber<HomeBean>(mContext) {
            @Override
            protected void _onNext(StatusCode<HomeBean> homeBeanStatusCode) {
                HomeBean homeBean = homeBeanStatusCode.getData();
                final List<RecommendhouseBean> recommendhouse = homeBean.getRecommendhouse();
                List<AdsBean> adsBeans = homeBean.getAds();
                List<WordOfMouthStoreBean> wordOfMouthStoreList = homeBean.getWordOfMouthStoreList();
                List<RecommendStyleList> recommendStyleList = homeBean.getRecommendStyleList();
                mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                if (adsBeans != null && adsBeans.size() > 0) {
                    mConvenientBanner.setPages(new CBViewHolderCreator<ImageViewHolder>() {
                        @Override
                        public ImageViewHolder createHolder() {
                            return new ImageViewHolder();
                        }
                    }, adsBeans)
                            .setPageIndicator(new int[]{R.drawable.noselect_circle_shape, R.drawable.select_circle_shape}) //设置两个点作为指示器
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL); //设置指示器的方向水平  居中
                }
                if (adsBeans.size() == 1) {
                    mConvenientBanner.setPointViewVisible(false);
                } else {
                    mConvenientBanner.setPointViewVisible(true);
                }

                if (recommendhouse != null && recommendhouse.size() > 0) {
                    /*热门楼盘*/
                    if (mHomeFragmentHorizontalScrollViewAdapter == null) {

                        mHomeFragmentHorizontalScrollViewAdapter = new HomeFragmentHorizontalScrollViewAdapter(mContext, recommendhouse);
                    } else {
                        mHomeFragmentHorizontalScrollViewAdapter.setTS(recommendhouse);
                    }
                    mIdHorizontalScrollViewFragmentHome.initDatas(mHomeFragmentHorizontalScrollViewAdapter);

                    if (recommendhouse.size()>2){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mIdHorizontalScrollViewFragmentHome.smoothScrollBy(200,0);
                            }
                        }, 0);
                    }


                    mIdHorizontalScrollViewFragmentHome.setOnItemClickListener(new MyHorizontalScrollView.OnItemClickListener() {
                        @Override
                        public void onClick(View view, int pos) {

                            HouseDetailsActivity.startActivity(mContext, recommendhouse.get(pos).getId() + "");
                        }
                    });
                }

                //品牌推荐
                if (wordOfMouthStoreList!=null &&wordOfMouthStoreList.size()>0){
                    mWordOfMouthStoreBeansList.clear();
                    mWordOfMouthStoreBeansList.addAll(wordOfMouthStoreList);
                    mBrandRecommandAdaptet.notifyDataSetChanged();
                }

                /*风格精选*/
                if (recommendStyleList!=null &&recommendStyleList.size()>0){

                    mRecommendStyleLists.clear();
                    mRecommendStyleLists.addAll(recommendStyleList);

                    mChoiceStyleGrideAdapter.notifyDataSetChanged();
                    LogUtils.i(TAG,"加载风格精选+++");

                }

            }

            @Override
            protected void _onError(String message) {
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);

            }
        }, "", lifecycleSubject, false, true);

        Observable<StatusCode<List<NoticeMessageBean>>> homeMessage = ApiUtils.getApi().getHomeMessage(Contans.defaultToken);

        HttpUtil.getInstance().toSubscribe(homeMessage, new ProgressSubscriber<List<NoticeMessageBean>>(mContext) {
            @Override
            protected void _onNext(StatusCode<List<NoticeMessageBean>> noticeMessageBeanStatusCode) {

                mNoticeMessageBeans = noticeMessageBeanStatusCode.getData();
                if (mNoticeMessageBeans.size()>0){

                    mLooperTextView.setTipList(mNoticeMessageBeans);
                }

            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
            }
        },"",lifecycleSubject,false,true);

    }

    @Override
    protected void initData() {
        super.initData();
        listDatas = new ArrayList<>();
        for (int i = 0; i < proName.length; i++) {
            listDatas.add(new ProductListBean(proName[i], iconResours[i]));
        }
        CornersProperty cornersProperty=new CornersProperty();
        cornersProperty.setCornersRadius(UIUtils.getDimens(R.dimen.dp_6));
        cornersProperty.setCornersType(CornersProperty.CornerType.ALL);
        mRoundCornersTransformation = new RoundCornersTransformation(mContext,cornersProperty);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        //总的页数，取整（这里有三种类型：Math.ceil(3.5)=4:向上取整，只要有小数都+1  Math.floor(3.5)=3：向下取整  Math.round(3.5)=4:四舍五入）
        totalPage = (int) Math.ceil(listDatas.size() * 1.0 / mPageSize);
        viewPagerList = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            //每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.layout_gridview, viewPager, false);
            mMyGridViewAdapterer = new HomeGridViewAdapter(mContext, listDatas, i, mPageSize);
            gridView.setAdapter(mMyGridViewAdapterer);

            mMyGridViewAdapterer.setOnItemOnclickListener(new HomeGridViewAdapter.OnItemOnclickListener() {
                @Override
                public void onItemClick(Context context, int pos, View view) {
                    Log.i("TAG", "position的值为：" + pos + "-->pos的值为：" + pos);
                 //   Toast.makeText(mContext, "你点击了 " + listDatas.get(pos).getProName(), Toast.LENGTH_SHORT).show();
                    switch (pos) {
                        case 0:
                            //新房
                            FloorHomeActivity.startActivity(context);
                            break;
                        case 1:
                            //买房赠券

                            MainActivity.goGoodsShop(mContext, 1);
                            break;

                        case 2:
                            MainActivity.goGoodsShop(mContext, 3);
                         //   ToastUtils.makeText("跳转物业管理");
                           // LivingPaymentActivity.myStartActvity(mContext);
  /*                        //生活缴费
                                    *//*WATER：缴水费
                            ELECTRIC：缴电费
                            GAS：缴燃气费
                            COMMUN：缴固话宽带
                            CATV：缴有线电视费
                            TRAFFIC：缴交通罚款
                            WUYE：缴物业费
                            HK：信用卡还款
                            CZ：手机充值*//*

                        String url="alipays://platformapi/startapp?appId=20000193";
//String url="alipays://platformapi/startapp?appId=20000193&url=/www/setNewAccount.htm?subBizType=";
        try {
            Intent intent;
            intent = Intent.parseUri(url,
                    Intent.URI_INTENT_SCHEME);
            intent.addCategory("android.intent.category.BROWSABLE");
            intent.setComponent(null);
            // intent.setSelector(null);
            startActivity(intent);

        } catch (Exception e) {
            ToastUtils.makeText("请安装支付宝");
        }*/

                            break;
                        //家用电器
                        case 3:
                            //家具家装
                            if (BaseApplication.isLoginSuccess) {
                                CouponsActivity.startActivity(mContext);

                            } else {
                                LoginActivity.startActivity(mContext, true);
                            }

                            break;

                    }


                }
            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        viewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));
        mTvLoaction.setText(StringUtils.isEmpty(mCity)? PreferencesUtils.getInstance().getString(Contans.CITY,"") :mCity );
        //品牌推荐
        mBrandRecommandAdaptet = new BrandRecommandAdaptet(mContext,mWordOfMouthStoreBeansList);
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(mBrandRecommandAdaptet);
        mHeaderAndFooterWrapper.addHeaderView(mHeadView);
        mHeaderAndFooterWrapper.addFootView(mFootView);
        mRecycleFragmentHome.setLayoutManager(new LinearLayoutManager(mContext));
        mRecycleFragmentHome.setItemAnimator(new DefaultItemAnimator());
        mRecycleFragmentHome.setAdapter(mHeaderAndFooterWrapper);



        //风格精选
        mRecommendStyleLists.clear();
        mChoiceStyleGrideAdapter = new ChoiceStyleGrideAdapter(mContext,mRecommendStyleLists);
        mMyGridView.setAdapter(mChoiceStyleGrideAdapter);
        mMyGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int classId = mRecommendStyleLists.get(position).getId();
                GoodsListActivity.startActivity(mContext,classId,2);
            }
        });

        retry();

        mRecycleFragmentHome.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                LogUtils.i(TAG, "当前最后一个：：" + lastVisibleItemPosition);
                if (lastVisibleItemPosition == 1) {

                    mLooperTextView.setTipList(mNoticeMessageBeans);
                }
            }
        });

    }


    public void setLocationCity(String city) {
        mCity = city;

        if (mTvLoaction != null) {

            mTvLoaction.setText(city );
        }
    }
    public void setLocationLatLng(LatLng latLng) {
        mLatLng = latLng;
    }
    @OnClick(R.id.iv_message_home_fragment)
    public void onViewClicked() {

        if (BaseApplication.isLoginSuccess) {
            MyMessageActivity.startActivity(mContext, BaseApplication.getUserId());
        } else {
            LoginActivity.startActivity(mContext,true);
        }

    }

    @OnClick(R.id.tv_city_fragment_home)
    public void onmCityViewClicked() {
        LocationMapActivity.startActivity(mContext,mCity,true,mLatLng);

    }
    public class ImageViewHolder implements Holder<AdsBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, AdsBean data) {
            Glide.with(context).load(data.getImg()).into(imageView);
            final String houseid = data.getHouseid();
            final long goodsId = data.getGoodsId();
       final      String type = data.getType();

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if ("0".equalsIgnoreCase(type)){
                        HouseDetailsActivity.startActivity(mContext, houseid);
                        //楼盘
                    }else if ("2".equalsIgnoreCase(type)){
                        //商品

                        GoodsDetailsActivity.startActivity(mContext,(int)goodsId);

                    }

                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(2000);
    }

    @Override
    public void onPause() {
        super.onPause();

        mConvenientBanner.stopTurning();
    }



    @Override
    protected void initEvent() {
        super.initEvent();
        mTvLookallFragmentHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FloorHomeActivity.startActivity(mContext);
            }
        });

        ivShopCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (BaseApplication.isLoginSuccess){

                ShopCarActivity.startActivity(mContext);

                }else {
                    LoginActivity.startActivity(mContext,true);
                }
            }
        });

        mRlNoticeRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mNoticeMessageBeans!=null &&mNoticeMessageBeans.size()>0){
                    int curTipIndex = (mLooperTextView.getCurTipIndex()+1)%mNoticeMessageBeans.size();
                    NoticeMessageBean noticeMessageBean = mNoticeMessageBeans.get(curTipIndex);
                    MessageBean messageBean=new MessageBean();
                    String title = noticeMessageBean.getTitle();
                    String content = noticeMessageBean.getContent();
                    String newsTime = noticeMessageBean.getNewsTime();
                    String type = noticeMessageBean.getType();
                    messageBean.setContent(content);
                    messageBean.setSummary(title);
                    messageBean.setTitle(type);
                    messageBean.setNewsTime(newsTime);
                    MessageDetailsActivity.startActivity(mContext,messageBean);
                }

            }
        });
    }
    @OnClick(R.id.rl_search_root_fragment_home)
    public void gotoSearch(){

        SearchGoodsActivity.startActivity(mContext);

    }

}
